package com.ins1st.plus.core.handler;

import com.alibaba.fastjson.JSON;
import com.ins1st.plus.base.ControllerResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: ins1st-plus
 * @description: 统一异常处理
 * @author: coderSun
 * @create: 2019-09-09 16:18
 **/
@ControllerAdvice
public class ExceptionHandle {

    /**
     * 处理异常拦截
     *
     * @param request
     * @param response
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Object handle4Exception(HttpServletRequest request, HttpServletResponse response, Exception e) {
        e.printStackTrace();
        return handle(request, response, "系统异常,请联系管理员");
    }

    /**
     * 处理返回值
     *
     * @param request
     * @param response
     * @param mesaage
     * @return
     */
    private Object handle(HttpServletRequest request, HttpServletResponse response, String mesaage) {
        if (isAjax(request)) {
            writeJson(response, ControllerResult.error(mesaage));
            return null;
        } else {
            ModelAndView mav = new ModelAndView();
            mav.setViewName("/pages/500.html");
            return mav;
        }
    }


    /**
     * 判断属于什么请求
     *
     * @param request
     * @return
     */
    private boolean isAjax(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null
                && "XMLHttpRequest".equals(request.getHeader("X-Requested-With")));
    }

    /**
     * 向response写数据
     *
     * @param response
     * @param r
     */
    protected void writeJson(HttpServletResponse response, ControllerResult r) {
        try {
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(r));
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
